<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var shipWithinDays = function (weights, days) {
      // 二分查找
      let l = Math.max(...weights), r = weights.reduce((a, i) => a + i, 0);
      function can(t) {
        let s = 0;
        let cnt = 0;
        for (let i of weights) {
          if (s + i > t) {
            cnt += 1;
            s = 0;
          }
          s += i;
        }
        return cnt + 1 <= days;
      }
      while (l < r) {
        // find first can.
        let m = Math.floor((l + r) / 2);
        if (can(m)) r = m;
        else l = m + 1;
      }
      return l;
    };
    console.log(shipWithinDays([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))
  </script>
</body>

</html>